package org.example.qqrobot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
import org.example.qqrobot.context.BaseContext;
import org.example.qqrobot.mapper.UserMapper;
import org.example.qqrobot.model.dto.UserInfoDTO;
import org.example.qqrobot.model.pojo.User;
import org.example.qqrobot.model.dto.UserLoginDTO;
import org.example.qqrobot.properties.WeChatProperties;
import org.example.qqrobot.service.UserService;
import org.example.qqrobot.util.HttpClientUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";


    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) throws Exception {
        Map map = new HashMap<>();

        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization");
        //调用微信接口服务,获取openid
        String json = HttpClientUtil.doGet(WX_LOGIN,map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        //判断openid是否为空，抛出业务异常
        if(openid == null){
            log.info("openid为空");
            throw new Exception();
        }

        log.info("openid为，{}",openid);
        //判断当前用户是否为新用户
        User user = userMapper.getByOpenid(openid);

        //如果是新的，就完成注册
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .name("用户" + System.currentTimeMillis())
                    .avatar("https://6d79-mycloud-8g5ijq9m4e6b00b4-1328315354.tcb.qcloud.la/moren.jpg?sign=3d3a79fcb13b44eb4bc15125123e01bb&t=1724506707")
                    .build();

            userMapper.insert(user);

        }

        //返回用户对象
        return user;

    }

    //用于获取userid
    @Override
    public User getMyUser(Long id) {
        return userMapper.getById(id);
    }

    @Override
    public void update(UserInfoDTO userInfoDTO) {
        User user = new User();
        BeanUtils.copyProperties(userInfoDTO, user);

        user.setId(BaseContext.getCurrentId());
        userMapper.update(user);
    }
}
